package halberd.filter;

import halberd.DataType;
import halberd.ImgFilter;
import halberd.data.ImgData;
import halberd.data.ImgDataFactory;

/**
 * 中值平衡
 * 
 * @author jiang
 *
 */
public class MidBalanceFilter implements ImgFilter{
	public ImgData process(ImgData input) {
		if (!canProcess(input)) {
			return null;
		}
		ImgData result = ImgDataFactory.createImgData(input.getWidth(), input.getHeight());
		int[][][] ints = input.getDatas();
		midBalance(ints, result.getDatas(), input.getWidth(), input.getHeight());
		result.setDataType(DataType.GRAY);
		return result;
	}

	private boolean canProcess(ImgData input) {
		if (input == null) {
			return false;
		}
		DataType dt = input.getDataType();
		if (dt == DataType.GRAY) {
			return true;
		}
		return false;
	}

	private void midBalance(int[][][] src, int[][][] dst, int Width, int Height) {
		int[] his = new int[256];
		int[] adj = new int[256];
		for (int i = 0; i < 256; ++i) {
			his[i] = 0;
			adj[i] = 0;
		}
		for (int i = 0; i < Width; ++i) {
			for (int j = 0; j < Height; ++j) {
				his[src[i][j][4]]++;
			}
		}
		int count = 0;
		int mid = 0;
		for (int i = 0; i < 256; ++i) {
			count += his[i];
			if (count >= Width * Height / 2) {
				mid = i;
				break;
			}
		}
		for (int i = 0; i <= mid; ++i) {
			adj[i] = (int) ((127.0 - 0) * (i - 0) / (mid - 0.0) + 0);
		}
		for (int i = mid + 1; i < 256; ++i) {
			adj[i] = (int) ((255.0 - 127) * (i - mid) / (255.0 - mid) + 127);
		}
		for (int i = 0; i < Width; ++i) {
			for (int j = 0; j < Height; ++j) {
				dst[i][j][4] =  adj[src[i][j][4]];
			}
		}
	}

}
